<?php
include_once 'field.class.php';

class field_mtypes extends field
{
    public $error;
    private $fomatlist;
    protected $fieldname = '多级分类';

    
    
    /**
     * 生成设置项
     * @author menghao
     * @param <string> $data
     * @return <string>
     */
    function settings($data='')
    {
    	$data = unserialize($data);
    	$data['ptype'] = isset($data['ptype']) && !empty ($data['ptype']) ? $data['ptype'] : '';
    	$setting = '';
        $setting .= '<label>选择父分类：'.form::select_parent_types('settings[ptype]', 'setting_ptype', '请选择', $data['ptype']).'</label> ';
        return $setting;
    }
    
    


    /**
     * 检查设置项数据
     * @author menghao
     * @param <array> $data 
     */
    function check_settings($data)
    {
       
        return true;
    }

    function check_data($data)
    {
        return parent::check_data($data);
    }
    
    function get_types($pcode)
    {
    	global $db;
    	$list = array();
    	$res = $db->query('select tcode,tname,parentcode from ' . DB_PRE .'type where topcode="'.$pcode.'" and status=' . STATUS_NORMAL . ' order by listorder desc, inputtime desc');
    	if(is_array($res))
    	{
    		foreach ($res as $v)
    		{
                    $list[$v['tcode']] = array($v['tname'],$v['parentcode']);
    		}
    	}
    	return $list;
    }
    
    function set_format($pcode=false)
    {
    	$pcode = $pcode==false ? $this->field_data['settings']['ptype'] : $pcode;
        $res = $this->get_types($pcode);
        $this->fomatlist = (!is_array($this->fomatlist) || sizeof($this->fomatlist)<=0) ? $res : $this->fomatlist + $res;
        if(is_array($res) && sizeof($res) > 0)
        {
            foreach ($res as $k=>$r)
            {
                $this->set_format($k);
            }
        }
    }
    
    function formate_value($str)
    {
    	$list = array(''=>'未设置');
    	$list = $list + $this->fomatlist;
        if(!isset($list[$str]))
        {
            return '未知类别';
        }
        else
        {
            $arr = array();
            $this->get_parent_value($str, $arr);
            return implode('&nbsp;', $arr);
        }
    }
    
    function get_parent_value($pstr,&$arr)
    {
        if(empty($pstr))
        {
            $arr = array('未设置');
            return true;
        }
        if($this->fomatlist[$pstr][1] != $this->field_data['settings']['ptype'])
        {
            $this->get_parent_value($this->fomatlist[$pstr][1], $arr);
        }
        $arr[] = $this->fomatlist[$pstr][0];
        return true;
    }

    function create_form($value='')
    {
    	global $db;
    	$pcode = $this->field_data['settings']['ptype'];
    	//$list = array(''=>'请选择');
    	$list = $this->get_types($pcode);
        $field = $this->field_data['field'];
        $form = form::level_select($list,$field, $field,$pcode, $value);
        return $form;
    }
}
?>
